package com.example.finalassignment.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.example.finalassignment.common.Cache;
import com.example.finalassignment.common.Constant;
import com.example.finalassignment.pojo.response.ResultDataResponse;
import com.example.finalassignment.pojo.response.ResultResponse;
import com.example.finalassignment.service.FilesService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/files")
public class FileController {

    private final FilesService filesService;

    public FileController(FilesService filesService) {
        this.filesService = filesService;
    }

    /**
     * 文件上传
     * @param file
     */
    @PostMapping("/upload")
    public ResultResponse upload(@RequestBody MultipartFile file) throws Exception {
        return filesService.upload(file);
    }

    /**
     * 文件下载
     */
    @GetMapping("/{uuid}")
    public void download(@PathVariable String uuid, HttpServletResponse httpServletResponse) throws IOException {

    }

    /**
     * 文件预览
     */
    @GetMapping("/shows/{uuid}")
    public void preview(@PathVariable String uuid, HttpServletResponse httpServletResponse) throws IOException {
        String[] strings = filesService.getFileAddress(uuid);
        File uploadFile = new File(strings[0] + strings[1]);
        httpServletResponse.setContentType("text/html;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        //读取数据
        outputStream.write(FileUtil.readBytes(uploadFile));
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 上传视频
     */
    @PostMapping("/video")
    public ResultResponse videos(@RequestBody MultipartFile file) throws Exception {
        return filesService.upload(file);
    }

    /**
     * 播放视频
     */
    @GetMapping("/video/{uuid}")
    public void videos(@PathVariable String uuid,HttpServletResponse httpServletResponse) throws Exception {
        String[] strings = filesService.getFileAddress(uuid);
        File uploadFile = new File(strings[0] + strings[1]);

        System.out.println(uploadFile);

        // 设置响应头信息
        httpServletResponse.setContentType("video/mp4");
        httpServletResponse.setHeader("Content-Disposition", "attachment; filename="+uuid + StrUtil.DOT + strings[1]);

        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        //读取数据
        outputStream.write(FileUtil.readBytes(uploadFile));
        outputStream.flush();
        outputStream.close();
    }
}
